package es.us.lsi.daw.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import es.us.lsi.daw.model.security.User;
import es.us.lsi.daw.servicios.MessageService;

@Controller
public class ControllerCambiarClave extends ControllerGenerico{

	@Autowired
	private MessageService	mensaje;

	@RequestMapping(value = "/privado/formCambiarClave.do", method = RequestMethod.GET)
	public String formCambiarClaveGET() {

		return "formCambiarClave";
	}

	@RequestMapping(value = "/privado/formCambiarClave.do", method = RequestMethod.POST)
	public String formUsuarioPOST(@RequestParam(value = "passwordHidden", required = false) String password, 
								  @RequestParam(value = "repeatPasswordHidden", required = false) String repeatPassword,
			ModelMap modelo, HttpServletRequest request, HttpSession sesion) {
		
		List<String> errores = new ArrayList<String>();
		if (password == null || password.isEmpty()) {
			errores.add(mensaje.obtenerMensaje("label.text.formuser.requerido.password"));
		} else if (repeatPassword == null || repeatPassword.isEmpty()) {
			errores.add(mensaje.obtenerMensaje("label.text.formuser.requerido.repetirClave"));
		} else {
			if (!password.equals(repeatPassword)) {
				errores.add(mensaje.obtenerMensaje("label.text.formuser.incorrecto.repetirClave"));
			}
		}
		if(!errores.isEmpty()) {
			modelo.addAttribute("errores", errores);
		}
		
		else {
			SecurityContext securityContext = (SecurityContext) sesion.getAttribute("SPRING_SECURITY_CONTEXT");
			if(securityContext != null){
				User usuario = (User) securityContext.getAuthentication().getPrincipal();
				usuario.setPassword(password);
				daoComun.guardarObjeto(usuario);
			}
		}
		return "jsonView";
	}
}
